import { ElMessage } from "element-plus";
import Cookies from "js-cookie";
import { createStore } from "vuex";
import router from "../router";
import { filterRoutes } from "../utils/filterRoutes";
import routesList from "../router/routes";
import { apiLogin } from "@/api/login";

import createPersistedState from "vuex-persistedstate";

export default createStore({
  state: {
    // 用户信息
    userInfo: {},
    // 路由表
    routesList: [],
  },
  mutations: {
    // 公共修改state
    set_state(state, action) {
      state[action.key] = action.data;
    },
  },
  actions: {
    async login({ commit, dispatch }, payload) {
      const res = await apiLogin(payload);

      ElMessage.success(res.msg);

      Cookies.set("token", res.token);

      dispatch("getRoutes", res.user.auth);

      commit("set_state", { key: "userInfo", data: res.user });
    },
    async getRoutes({ commit }, auth) {
      let res = filterRoutes(routesList, auth);

      res.forEach((item) => {
        router.addRoute(item);
      });

      router.push("/");

      commit("set_state", { key: "routesList", data: res });
    },
  },
  modules: {},
  plugins: [
    createPersistedState({
      storage: window.sessionStorage,
      reducer(state) {
        return {
          // 只储存state中的user
          userInfo: state.userInfo,
        };
      },
    }),
  ],
});
